<template>
  <div class="profile-container">
    <el-card class="profile-card">
      <div slot="header" class="card-header">
        <span>个人信息</span>
      </div>
      
      <!-- 头像上传区域 -->
      <div class="avatar-container">
        <el-upload
          class="avatar-uploader"
          action="/api/file/upload"
          :show-file-list="false"
          :on-success="handleAvatarSuccess"
          :before-upload="beforeAvatarUpload"
        >
          <img v-if="userInfo.avatarUrl" :src="'/api/file/get/' + userInfo.avatarUrl" class="avatar">
          <i v-else class="el-icon-plus avatar-uploader-icon"></i>
        </el-upload>
        <div class="avatar-tip">点击更换头像</div>
      </div>

      <!-- 基本信息表单 -->
      <el-form 
        :model="userForm" 
        :rules="rules"
        ref="userForm" 
        label-width="80px"
        class="profile-form"
      >
        <el-form-item label="用户名" prop="username">
          <el-input v-model="userForm.username" disabled></el-input>
        </el-form-item>
        
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="userForm.email"></el-input>
        </el-form-item>
        
        <el-form-item label="手机号" prop="phone">
          <el-input v-model="userForm.phone"></el-input>
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="updateProfile" :loading="updating">
            保存修改
          </el-button>
        </el-form-item>
      </el-form>

      <!-- 修改密码表单 -->
      <div class="password-section">
        <h3>修改密码</h3>
        <el-form 
          :model="passwordForm" 
          :rules="passwordRules"
          ref="passwordForm" 
          label-width="100px"
        >
          <el-form-item label="原密码" prop="oldPassword">
            <el-input 
              v-model="passwordForm.oldPassword" 
              type="password"
              show-password
            ></el-input>
          </el-form-item>
          
          <el-form-item label="新密码" prop="newPassword">
            <el-input 
              v-model="passwordForm.newPassword" 
              type="password"
              show-password
            ></el-input>
          </el-form-item>
          
          <el-form-item label="确认新密码" prop="confirmPassword">
            <el-input 
              v-model="passwordForm.confirmPassword" 
              type="password"
              show-password
            ></el-input>
          </el-form-item>

          <el-form-item>
            <el-button type="primary" @click="updatePassword" :loading="changingPassword">
              修改密码
            </el-button>
          </el-form-item>
        </el-form>
      </div>
    </el-card>
  </div>
</template>

<script>
import request from '@/utils/request'

export default {
  name: 'UserProfile',
  data() {
    // 确认密码的验证规则
    const validateConfirmPassword = (rule, value, callback) => {
      if (value !== this.passwordForm.newPassword) {
        callback(new Error('两次输入的密码不一致'))
      } else {
        callback()
      }
    }

    return {
      userInfo: JSON.parse(localStorage.getItem('userInfo') || '{}'),
      userForm: {
        username: '',
        email: '',
        phone: '',
        avatarUrl: ''
      },
      passwordForm: {
        oldPassword: '',
        newPassword: '',
        confirmPassword: ''
      },
      updating: false,
      changingPassword: false,
      rules: {
        email: [
          { required: true, message: '请输入邮箱地址', trigger: 'blur' },
          { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' }
        ],
        phone: [
          { required: true, message: '请输入手机号', trigger: 'blur' },
          { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号', trigger: 'blur' }
        ]
      },
      passwordRules: {
        oldPassword: [
          { required: true, message: '请输入原密码', trigger: 'blur' },
          { min: 6, message: '密码长度不能小于6位', trigger: 'blur' }
        ],
        newPassword: [
          { required: true, message: '请输入新密码', trigger: 'blur' },
          { min: 6, message: '密码长度不能小于6位', trigger: 'blur' }
        ],
        confirmPassword: [
          { required: true, message: '请再次输入新密码', trigger: 'blur' },
          { validator: validateConfirmPassword, trigger: 'blur' }
        ]
      }
    }
  },
  created() {
    this.fetchUserInfo()
  },
  methods: {
    async fetchUserInfo() {
      try {
        const res = await request.get('/api/user/info')
        this.userForm = { ...res.data }
        // 更新本地存储的用户信息
        localStorage.setItem('userInfo', JSON.stringify(res.data))
      } catch (error) {
        this.$message.error('获取用户信息失败')
      }
    },
    beforeAvatarUpload(file) {
      const isImage = file.type.startsWith('image/')
      const isLt2M = file.size / 1024 / 1024 < 2

      if (!isImage) {
        this.$message.error('只能上传图片文件!')
        return false
      }
      if (!isLt2M) {
        this.$message.error('图片大小不能超过 2MB!')
        return false
      }
      return true
    },
    async handleAvatarSuccess(res) {
      try {
        await request.put('/api/user/avatar', { avatarUrl: res.data })
        this.userForm.avatarUrl = res.data
        this.$message.success('头像更新成功')
        // 更新本地存储的用户信息
        const userInfo = JSON.parse(localStorage.getItem('userInfo') || '{}')
        userInfo.avatarUrl = res.data
        localStorage.setItem('userInfo', JSON.stringify(userInfo))
      } catch (error) {
        this.$message.error('头像更新失败')
      }
    },
    async updateProfile() {
      try {
        await this.$refs.userForm.validate()
        this.updating = true
        await request.put('/api/user/profile', this.userForm)
        this.$message.success('个人信息更新成功')
        // 更新本地存储的用户信息
        localStorage.setItem('userInfo', JSON.stringify(this.userForm))
      } catch (error) {
        this.$message.error(error.message || '更新失败')
      } finally {
        this.updating = false
      }
    },
    async updatePassword() {
      try {
        await this.$refs.passwordForm.validate()
        this.changingPassword = true
        await request.put('/api/user/password', this.passwordForm)
        this.$message.success('密码修改成功，请重新登录')
        // 清除登录信息，跳转到登录页
        localStorage.removeItem('token')
        localStorage.removeItem('userInfo')
        this.$router.push('/login')
      } catch (error) {
        this.$message.error(error.message || '密码修改失败')
      } finally {
        this.changingPassword = false
      }
    }
  }
}
</script>

<style scoped>
.profile-container {
  padding: 20px;
  max-width: 800px;
  margin: 0 auto;
}

.profile-card {
  margin-bottom: 20px;
}

.card-header {
  font-size: 18px;
  font-weight: bold;
}

.avatar-container {
  text-align: center;
  margin-bottom: 30px;
}

.avatar-uploader {
  display: inline-block;
}

.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 50%;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}

.avatar-uploader .el-upload:hover {
  border-color: #409EFF;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 120px;
  height: 120px;
  line-height: 120px;
  text-align: center;
  border-radius: 50%;
}

.avatar {
  width: 120px;
  height: 120px;
  border-radius: 50%;
  display: block;
}

.avatar-tip {
  color: #909399;
  font-size: 12px;
  margin-top: 10px;
}

.profile-form {
  max-width: 400px;
  margin: 0 auto;
}

.password-section {
  margin-top: 40px;
  padding-top: 20px;
  border-top: 1px solid #EBEEF5;
}

.password-section h3 {
  margin-bottom: 20px;
}
</style> 